package com.ruoyi.config;

import cn.hutool.core.util.RandomUtil;
import com.ruoyi.service.impl.OnMessageCallback;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author: 黄龙
 * @Date: 2022/5/7 18:18
 */
@Slf4j
@Configuration
public class MqttConfig {

    @Value("${mqtt.pubTopic}")
    private String pubTopic;
    @Value("${mqtt.qos}")
    private int qos;
    @Value("${mqtt.broker}")
    private String broker;
    @Value("${mqtt.clientId}")
    private String clientId;

    @Bean
    public MqttClient mqttClient() throws MqttException {
        MemoryPersistence persistence = new MemoryPersistence();
        MqttClient client = new MqttClient(broker, clientId + ":" + RandomUtil.randomNumbers(3), persistence);
        // MQTT 连接选项
        MqttConnectOptions connOpts = new MqttConnectOptions();
       // connOpts.setUserName("emqx_test");
       // connOpts.setPassword("emqx_test_password".toCharArray());
        // 保留会话
        connOpts.setCleanSession(true);
        // 设置回调
        client.setCallback(new OnMessageCallback());
        // 建立连接
        log.info("<--- MQTT Connecting to broker: {}" , broker);
        client.connect(connOpts);
        client.subscribe(pubTopic);
        log.info("<--- MQTT Connected");
        return client;
    }
}
